<template>
    <div class="flex flex-col gap-2 p-8">
        <div class="flex flex-row justify-between items-center mb-4">
            <div class="text-lg font-semibold text-black-100">新增
                <span class="text-sm">书籍</span>
            </div>
        </div>
        <n-form class="bg-gray-50 p-8 rounded-lg" ref="formRef" :label-width="80" :model="formValue" :rules="rules"
            size="small">
            <n-form-item label="名称" path="name">
                <n-input v-model:value="formValue.name" placeholder="输入名称" />
            </n-form-item>
            <n-form-item label="作者" path="author">
                <n-input v-model:value="formValue.author" placeholder="输入作者" />
            </n-form-item>
            <n-form-item label="类型" path="type_id">
                <n-select v-model:value="formValue.category_id" placeholder="选择类型"  :options="categories" label-field="name" value-field="id"/>
            </n-form-item>
            <n-form-item label="出版日期" path="publication_year">
                <n-date-picker v-model:value="formValue.publication_year" type="date"  placeholder="出版日期" />
            </n-form-item>
            <n-form-item label="剩余数量" path="available">
                <n-input-number v-model:value="formValue.available" placeholder="剩余数量" />
            </n-form-item>
            <n-form-item>
                <n-button attr-type="button" @click="handleValidateClick">
                    发布
                </n-button>
            </n-form-item>
        </n-form>
    </div>

</template>

<script setup>

import { defineComponent, ref, onMounted } from "vue";
import { CreateBook, GetCategories } from "../../wailsjs/go/main/App.js"
import { useMessage } from "naive-ui";
import { useRouter } from "vue-router";
const router = useRouter();
const message = useMessage();
const categories = ref([]);
const formRef = ref();
// 获取当前时间戳
const formValue = ref({
    name: "",
    author: "",
    category_id: "",
    publication_year: new Date().getTime(),
    available: 0
})
const rules = {
    name: {
        required: true,
        message: "请输入姓名",
        trigger: "blur"
    },
    author: {
        required: true,
        message: "请输入作者",
        trigger: ["input", "blur"]
    },
    available: {
        required: true,
        message: "请输入剩余数量",
    }
}

const handleValidateClick = (e) => {
    e.preventDefault();
    formRef.value?.validate((errors) => {
        if (!errors) {
            console.log(formValue.value);
            CreateBook(formValue.value.name, formValue.value.author, formValue.value.category_id, formValue.value.publication_year, formValue.value.available).then(res => {
                router.push({name: "books"})
            })
        } else {
            console.log(errors);
            message.error("Invalid");
        }
    });
}

onMounted(() => {
    GetCategories().then(res => {
        console.log(res);
        categories.value = res;
    })
})

</script>